package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.html.EscapeUtil;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;

@Service("common")
public class CommonServiceImpl implements ICommonService {

    private static final Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);

    @Autowired
    private SysStudentMapper studentMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysRoomService roomService;

    @Autowired
    private ISysStoreService storeService;

    @Autowired
    private SysTrainMapper trainMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private SysDictDataMapper dictDataMapper;
    /**
     * 根据字典类型查询字典数据信息
     *
     * @param dictType 字典类型
     * @return 参数键值
     */
    public List<SysDictData> getType(String dictType) {
        List<SysDictData> sysDictDataList = new ArrayList<SysDictData>();
        if (dictType.toLowerCase().equals("sys_dept")) {
            List<SysDept> sysDeptList = deptService.selectDeptList(new SysDept());
            for (SysDept item : sysDeptList) {
                SysDictData dict = new SysDictData();
                if (item.getAncestors().split(",").length == 3) {
                    dict.setDictLabel(item.getDeptName());
                    dict.setDictValue(item.getDeptId().toString());
                    sysDictDataList.add(dict);
                }
            }
        } else if (dictType.toLowerCase().equals("sys_room")) {
            List<SysRoom> sysRoomList = roomService.selectSysRoomList(new SysRoom());
            for (SysRoom item : sysRoomList) {
                SysDictData dict = new SysDictData();
                dict.setDictLabel(item.getRoomName());
                dict.setDictValue(item.getRoomId().toString());
                sysDictDataList.add(dict);
            }
        } else if (dictType.toLowerCase().equals("sys_room_master")) {
            SysRole rm = new SysRole();
            rm.setRoleName("班主任");
            List<SysRole> roles = roleMapper.selectRoleList(rm);
            SysUser um = new SysUser();
            um.setRoles(roles);
            List<SysUser> sysUserList = userMapper.selectAllocatedList(um);
            for (SysUser item : sysUserList) {
                SysDictData dict = new SysDictData();
                dict.setDictLabel(item.getUserName());
                dict.setDictValue(item.getUserId().toString());
                sysDictDataList.add(dict);
            }
//        }else if(dictType.toLowerCase().equals("sys_course")) {
//            List<SysCourse> sysCourseList = courseService.selectSysCourseList(new SysCourse());
//            for (SysCourse item : sysCourseList) {
//                SysDictData dict = new SysDictData();
//                dict.setDictLabel(item.getCourseName());
//                dict.setDictValue(item.getCourseId().toString());
//                sysDictDataList.add(dict);
//            }
        } else if (dictType.toLowerCase().equals("sys_store")) {
            List<SysStore> sysStoreList = storeService.selectSysStoreList(new SysStore());
            for (SysStore item : sysStoreList) {
                SysDictData dict = new SysDictData();
                dict.setDictLabel(item.getStoreName());
                dict.setDictValue(item.getStoreId().toString());
                sysDictDataList.add(dict);
            }
        }
        return sysDictDataList;
    }

    public Object getMasterSelectJson() {

        SysRole rm = new SysRole();
        rm.setRoleName("班主任");
        List<SysRole> roles = roleMapper.selectRoleList(rm);
        List<SysDept> sysDeptList = deptService.selectDeptList(new SysDept());
        SysUser um = new SysUser();
        um.setRoleId(roles.get(0).getRoleId());
        List<SysUser> sysUserList = userMapper.selectAllocatedList(um);

        List<CxSelect> cxDeptList = new ArrayList<CxSelect>();
        for (SysDept item : sysDeptList) {
            CxSelect cxSelectDEPT = new CxSelect();
            cxSelectDEPT.setV(item.getDeptId().toString());
            cxSelectDEPT.setN(item.getDeptName());
            if (item.getAncestors().split(",").length == 3) {
                List<CxSelect> cxList = new ArrayList<CxSelect>();
                for (SysUser user : sysUserList) {
                    if (user.getDeptId().equals(item.getDeptId())) {
                        CxSelect cxSelectUSER = new CxSelect();
                        cxSelectUSER.setN(user.getUserName());
                        cxSelectUSER.setV(user.getUserId().toString());
                        cxList.add(cxSelectUSER);
                    }
                }
                cxSelectDEPT.setS(cxList);
                cxDeptList.add(cxSelectDEPT);
            }
        }
        return JSON.toJSON(cxDeptList);
    }

    public Object getStoreSelectJson() {
        List<SysDictData> cityList = dictDataMapper.selectDictDataByType("sys_city_list");
        List<SysStore> sysStoreList = storeService.selectSysStoreList(new SysStore());
        List<CxSelect> cxStoreList = new ArrayList<CxSelect>();
        for (SysDictData item : cityList) {
            CxSelect cxSelectCITY = new CxSelect();
            cxSelectCITY.setV(item.getDictLabel());
            cxSelectCITY.setN(item.getDictValue());
            List<CxSelect> cxList = new ArrayList<CxSelect>();
            for (SysStore store : sysStoreList) {
                if(store.getCity().equals(item.getDictLabel())) {
                    CxSelect cxSelectSTORE = new CxSelect();
                    cxSelectSTORE.setN(store.getStoreName());
                    cxSelectSTORE.setV(store.getStoreId().toString());
                    cxList.add(cxSelectSTORE);
                }
            }
            cxSelectCITY.setS(cxList);
            cxStoreList.add(cxSelectCITY);
        }
        return JSON.toJSON(cxStoreList);
    }

    public String getStatData(String statType) {
        int count = 0;
        switch (statType) {
            case "student.count":
                count = studentMapper.selectSysStudentList(new SysStudent()).size();
                return String.format("%d", count);
            case "room.count":
                count = roomService.selectSysRoomList(new SysRoom()).size();
                return String.format("%d", count);
            case "store.count":
                count = storeService.selectSysStoreList(new SysStore()).size();
                return String.format("%d", count);
            case "train.count":
                count = trainMapper.selectSysTrainList(new SysTrain()).size();
                return String.format("%d", count);
            case "money.count":
                count = trainMapper.selectMoneySum();
                return String.format("%d", count);
            case "dept.count":
                List<SysDept> deptList = deptService.selectDeptList(new SysDept());
                for (SysDept item : deptList) {
                    if (item.getAncestors().split(",").length == 3) {
                        count++;
                    }
                }
                return String.format("%d", count);
        }
        return "";
    }

    public String getRoomByUserId() {
        Long userId = ShiroUtils.getUserId();
        try {
            SysUser user = userMapper.selectUserById(userId);
            SysRoom room = roomService.selectSysRoomByUserId(userId);
            SysDept dept = deptService.selectDeptById(room.getDept().getDeptId());
            return String.format("%s / %s / %s", dept.getDeptName(), room.getRoomName(), user.getUserName());
        }catch (NullPointerException ex){
            return "错误：当前老师未设置所在班级";
        }
    }

    /**
     * 导入用户数据
     *
     * @param sysStudentList  用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importSysStudent(List<SysStudent> sysStudentList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(sysStudentList) || sysStudentList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysStudent student : sysStudentList) {
            try {
                // 验证是否存在这个用户
                SysStudent u = studentMapper.selectSysStudentByStudentId(1L);
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, student);
//                    deptService.checkDeptDataScope(student.getDeptId());
//                    String password = configService.selectConfigByKey("sys.student.initPassword");
//                    student.setPassword(Md5Utils.hash(student.getLoginName() + password));
                    student.setCreateBy(operName);
                    studentMapper.insertSysStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + student.getStudentName() + " 导入成功");
                }
                if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, student);
//                    checkSysStudentAllowed(u);
//                    checkStudentDataScope(u.getStudentId());
//                    deptService.checkDeptDataScope(student.getDeptId());
                    student.setStudentId(u.getStudentId());
                    student.setUpdateBy(operName);
                    studentMapper.updateSysStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学员 " + student.getStudentName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + student.getStudentName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String loginName = student.getStudentName();
                if (ExceptionUtil.isCausedBy(e, ConstraintViolationException.class)) {
                    loginName = EscapeUtil.clean(loginName);
                }
                String msg = "<br/>" + failureNum + "、账号 " + loginName + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
